// 引入依赖模块
const express = require('express')
const cors = require('cors')
const Mock = require('mockjs')
// 引入路由模块
const sessionsRoute = require('./routes/sessions')
const departmentsRoute = require('./routes/departments')
const doctorsRoute = require('./routes/doctors')
const patientsRoute = require('./routes/patients')
const ordersRoute = require('./routes/orders')
const statisticsRoute = require('./routes/statistics')
const diseaseRoute = require('./routes/disease')

// token 辅助模块
const Token = require('./utils/token')

// 创建 Express 应用
const app = express()

// 处理跨域
app.use(cors())

// 处理请求主体数据
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// 托管静态资源
app.use(express.static('public'))

// 使用路由中间件
app.use('/api/v1/sessions', sessionsRoute)
app.use('/api/v1/departments', departmentsRoute)
app.use('/api/v1/doctors', doctorsRoute)
app.use('/api/v1/patients', patientsRoute)
app.use('/api/v1/orders', ordersRoute)
app.use('/api/v1/disease', diseaseRoute)
app.use('/api/v1/statistics', statisticsRoute)

// 拦截用户请求与响应，验证 token 是否正确（中间件）
// app.use((req, res, next) => {
//   // console.log('请求头：', req.headers)
//   // 从请求头中获取 token 数据
//   const token = req.headers.authorization
//   // 校验 token
//   try {
//     Token.verifyToken(token)
//     // 如果 token 校验通过，则说明无问题，继续向后处理
//     next()
//   } catch (error) {
//     // 如果 token 校验有问题，则返回响应
//     res.json(error.data)
//   }
// })

// app.use('/api/v1/users', usersRoute)


// websocket
const http = require('http')
const websocketServer = require('websocket').server
// 创建 http 服务器
const server = http.createServer(app)

server.listen(9527, () => console.log('server running at http://localhost:9527'))

// websocket server
const sockets = []
let id = 1
const list = []
const wsServer = new websocketServer({
  httpServer: server
})

wsServer.on('request', (request) => {
  let connection = request.accept(null, request.origin)
  sockets.push(connection)
  connection.sendUTF(JSON.stringify(list))
  connection.on('close', () => {
    connection = null
    // 释放资源：TODO...
  })
})
const random = (min, max) => Math.floor(Math.random() * (max - min)) + min
const genData = () => {
  list.unshift(Mock.mock({
    id: id++,
    name: '@cname',
    department: '@ctitle(3,5)',
    'fee|5-15': 5,
    time: '@date(yyyy-MM-dd)'
  }))
  if (list.length > 10) {
    list.pop()
  }
  sockets.forEach(socket => {
    socket.sendUTF(JSON.stringify(list))
  })

  setTimeout(genData, random(5, 15) * 1000)
}

genData()
